package org.thrift;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thrift.service.QueryResult;
import org.thrift.service.QueryService;

/**
 * @author donald 2018年3月12日 下午2:01:37
 */
public class ThriftClient {
	private static final Logger log = LoggerFactory.getLogger(ThriftClient.class);
	private final static String DEFAULT_HOST = "127.0.0.1";
	private final static int DEFAULT_PORT = 30001;
	private final static int DEFAULT_TIMEOUT = 5000;
	private final static int DEFAULT_QUERY_CODE = 1;

	public static void main(String[] args) {
		try {
			TTransport tTransport = getTTransport();
			TProtocol protocol = new TBinaryProtocol(tTransport);
			QueryService.Client client = new QueryService.Client(protocol);
			QueryResult result = client.query(DEFAULT_QUERY_CODE);
			log.info("code={} ,msg={}",result.code,result.msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return
	 * @throws Exception
	 */
	private static TTransport getTTransport() throws Exception {
		try {
			TTransport tTransport = getTTransport(DEFAULT_HOST, DEFAULT_PORT, DEFAULT_TIMEOUT);
			if (!tTransport.isOpen()) {
				tTransport.open();
			}
			return tTransport;
		} catch (Exception e) {
			log.error("获取TTransport异常", e);
		}
		return null;
	}

	/**
	 * @param host
	 * @param port
	 * @param timeout
	 * @return
	 */
	private static TTransport getTTransport(String host, int port, int timeout) {
		final TSocket tSocket = new TSocket(host, port, timeout);
		final TTransport transport = new TFramedTransport(tSocket);
		return transport;
	}

}
